package cn.kgc.spring.factory;

import cn.kgc.spring.dao.NewUserDaoImpl;
import cn.kgc.spring.dao.UserDao;
import cn.kgc.spring.dao.UserDaoImpl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author: mosin
 * @version: v1.0  2022/10/11
 * 工厂类  降低代码的耦合
 *
 */
public class BeanFactory {

    private static Map<String,Object> beans = new HashMap<>();

    static {
        //加载配置文件 创建对象
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
            Enumeration<Object> keys = properties.keys();
            // 遍历key
            while (keys.hasMoreElements()){
                String key =(String) keys.nextElement();
                String path = (String) properties.get(key);
                Class<?> clazz = Class.forName(path);
                Object o = clazz.newInstance();
                beans.put(key, o);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //public static UserDao getUserDaoImpl(){
    //    return  new UserDaoImpl();
    //}

    //public static UserDao getUserDaoImpl(){
    //    return  new NewUserDaoImpl();
    //}


    public static UserDao getUserDaoImpl(String BeanName){
        //使用反射创建对象
        try {
            Class<?> clazz = Class.forName(BeanName);
            UserDao o = (UserDao) clazz.newInstance();
            return  o;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static Object getBean(String BeanName){
        //使用反射创建对象
        try {
            Class<?> clazz = Class.forName(BeanName);
            Object o =  clazz.newInstance();
            return  o;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    //public static  <T> T  getBean(String BeanName,Class<T> className){
    //    //使用反射创建对象
    //    try {
    //        Class<?> clazz = Class.forName(BeanName);
    //        Object o = clazz.newInstance();
    //        return className.cast(o);
    //    } catch (Exception e) {
    //        e.printStackTrace();
    //    }
    //    return null;
    //}

    /**
     *
     * @param BeanName    map  key
     * @param className
     * @param <T>
     * @return
     */
    public static  <T> T  getBean(String BeanName,Class<T> className){
        Object o = beans.get(BeanName);
        return className.cast(o);
    }

}
